<template>
  <div class="bg-container">
    <div class="login-register-container">
      <div class="tabs">
        <span :class="{ 'active':!isRegister }" @click="isRegister = false">登录</span>
        <span :class="{ 'active': isRegister }" @click="isRegister = true">注册</span>
      </div>
      <transition name="form-transiton" mode="out-in">
        <!-- 登录相关表单 -->
        <div v-if="!isRegister" class="login-form-wrapper">
          <el-form class="login-form" ref="loginForm" :model="form" :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              @keyup.native.enter="handleLogin"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 注册相关表单 -->
        <div v-else class="register-form-wrapper">
          <el-form class="register-form" ref="registerForm" :model="form" :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="repassword">
              <el-input v-model="form.repassword" type="password"
              placeholder="请再次输入密码"
              prefix-icon="el-icon-lock"
              @keyup.native.enter="handleRegister"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRegister" :loading="loading">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
  </div>
</div>
</template>
<script>
import { login, register } from '@/api/user'
import { mapActions } from 'vuex'

export default {
  name: 'LoginPage',
  data () {
    return {
      isRegister: false,
      loading: false,
      form: {
        username: '',
        password: '',
        repassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '用户名长度在5到10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{6,12}$/,
            message: '密码长度在6到12个字符之间',
            trigger: 'blur'
          }
        ],
        repassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{6,12}$/,
            message: '密码长度在6到12个字符之间',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) { // 改用传统函数
              if (value !== this.form.password) { // 这里可以正确访问到form数据
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            }.bind(this), // 绑定当前Vue实例上下文
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    ...mapActions('user', ['saveUserInfo']),

    // 处理登录
    handleLogin () {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            console.log('表单验证通过，准备登录')
            // 构建登录DTO对象 - 符合UserLoginDTO格式
            const loginDTO = {
              username: this.form.username,
              password: this.form.password
              // id字段不需要前端提供，后端会自动查询
            }
            console.log('发送登录请求前...')
            // 调用登录接口
            const res = await login(loginDTO)
            console.log('登录响应数据:', res)
            if (res.code === 200) {
              // 登录成功，获取UserLoginVO数据
              const userLoginVO = res.data
              console.log('登录成功，用户数据:', userLoginVO)
              // 保存用户信息到Vuex
              this.saveUserInfo({
                id: userLoginVO.id,
                username: userLoginVO.username,
                token: userLoginVO.token
              })
              this.$message.success('登录成功')
              // 跳转到首页，添加错误捕获
              this.$router.push('/').catch(err => {
                console.warn('路由导航被取消:', err.message)
              })
            } else {
              this.$message.error(res.msg || '登录失败')
            }
          } catch (error) {
            console.error('登录处理过程中发生错误:', error)
            if (error.message && error.message.includes('Network Error')) {
              this.$message.error('网络连接错误，请检查后端服务器是否启动')
            } else {
              this.$message.error('登录失败: ' + (error.message || '未知错误'))
            }
          } finally {
            this.loading = false
          }
        } else {
          console.log('登录表单验证失败')
          return false
        }
      })
    },
    // 处理注册
    handleRegister () {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            // 构建注册对象
            const registerData = {
              username: this.form.username,
              password: this.form.password
            }
            // 调用注册接口
            const res = await register(registerData)
            if (res.code === 200) {
              this.$message.success('注册成功，请登录')
              this.isRegister = false // 切换到登录页
              this.form.password = '' // 清空密码
              this.form.repassword = ''
            } else {
              this.$message.error(res.msg || '注册失败')
            }
          } catch (error) {
            console.error('注册请求失败', error)
            this.$message.error('注册失败，请稍后重试')
          } finally {
            this.loading = false
          }
        } else {
          console.log('注册表单验证失败')
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.bg-container{
  background-image: url('@/assets/login_bg.png');
  background-size:cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.login-register-container {
  width: 500px;
  background: rgba(255, 255, 255, 0.8); /* 调整背景透明度 */
  color: #333;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.tab{
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.tabs span {
  padding: 5px 15px;
  cursor: pointer;
  border-bottom: 5px solid transparent;
  transition: border-bottom 0.3s ease;
}

.tabs span.active {
  border-bottom: 2px solid #f2994a;
}
.login-form-wrapper,
.register-form-wrapper {
  padding: 20px;
}
.form-transition-enter-active,
.form-transition-leave-active {
  transition: opacity 0.3s ease;
}

.form-transition-enter,
.form-transition-leave-to {
  opacity: 0;
}

</style>
